package io.renren.modules.app.controller;
import io.renren.modules.app.entity.Response;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;

/**
 * ClassName: ImageUploadController
 * Package: io.renren.modules.app.controller
 * Description:
 * 图片上传接口
 * @Author zzy
 * @Create 2024/4/21 19:49
 * @Version 1.0
 */


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/app/userpic")
public class ImageUploadController {
    // 更改 DIRECTORY 值为 "/taihuoPicture"
    private final String DIRECTORY = "/taihuoPicture";

    @PostMapping("/upload")
    public Response upload(@RequestParam("file") MultipartFile file) throws IOException {
        // 获得文件的原始名字
        String originalFilename = file.getOriginalFilename();

        // 创建用于格式化日期时间的格式化器
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        // 得到当前的日期时间
        LocalDateTime now = LocalDateTime.now();

        // 使用日期时间格式化器来格式化当前日期时间，然后附加原始文件名
        String fileName = dtf.format(now) + "_" + originalFilename;

        try {
            // 拼接完整的保存图片的本地路径
            String fullPath = DIRECTORY + "/" + fileName;

            // 保存图片
            file.transferTo(new File(fullPath));

            // 返回图片的URL，假设服务器地址是 http://120.27.140.32:90（服务器地址）
            String imageUrl = "http://120.27.140.32:90" + "/" + fileName;
            return new Response(0, "success", imageUrl);
        } catch (Exception e) {
            return new Response(500, "服务器异常：" + e.getMessage(), null);
        }
    }
}
